$NG.AllReady(function (editPage, { useAction, useUpdateRows, useValuesChange, useDataIndexChange, useClick }) {
    const headerTable = $NG.getCmpApi("p_form_ywgcwb_JL");
    const mstform = $NG.getCmpApi("p_form_ywgcwb_JL");
    const dgrid1 = $NG.getCmpApi("p_form_ywgcwb_JL_d1");
    const dgrid2 = $NG.getCmpApi("p_form_ywgcwb_JL_d2");
    const dgrid3 = $NG.getCmpApi("p_form_ywgcwb_JL_d3");
    getCntCount("p_form_ywgcwb_JL", "u_fbht_name", () => {
        getCntMInfoByPhid();
        getCntIndoByGzdyAndSbqd();

    });
    $NG.updateUI((updater) => {
        updater.editGrid.p_form_ywgcwb_JL_d3.u_bg_qty.setProps({
            hidden: true,
        });
    });

    useValuesChange(async ({ args }) => {
        await getPtInfoByPhid();
        await getWgsbD3Qty();
        await getCntIndoByGzdyAndSbqd();
        filterCnt();
        cntDFilter();
        getCntCount("p_form_ywgcwb_JL", "u_fbht_name", () => {
            getCntMInfoByPhid();
            getCntIndoByGzdyAndSbqd();

        });
    }, "p_form_ywgcwb_JL.phid_pc");
    useValuesChange(async ({ args }) => {
        await getCntMInfoByPhid();
        await getWgsbD3Qty();
        getWgsbHeadInfo()
        setTimeout(() => {
            getCntIndoByGzdyAndSbqd();
        }, 300);
    }, "p_form_ywgcwb_JL.u_fbht_name");

    useDataIndexChange(({ args }) => {
        const row = args[0];
        let total_aty = 0;
        if (window._lsz_catch_qty) {
            window._lsz_catch_qty.forEach((item) => {
                if (item.u_fbht_code == row.u_fbht_code) {
                    total_aty = item.bq_qty;
                }
            });
        }
        row.u_ljjl_qty = (Number(total_aty) || 0) + (Number(row.u_bqjlsl) || 0);
        row.u_remain_qty = Number(row.u_bqjlsl) || 0;
        if (row.u_ljjl_qty > (Number(row.u_bg_qty) || 0) + (Number(row.u_fbqd_qty) || 0)) {
            row.u_ljjl_qty = Number(total_aty) || 0;
            row.u_bqjlsl = null;
            row.u_remain_qty = null;
            $NG.alert("累计数量已超出");
        }
        dgrid3.refreshView();
    }, "u_bqjlsl");

    useUpdateRows(({ args }) => {
        console.log(`useUpdateRows1`,);
        sumAmt()
    }, "p_form_ywgcwb_JL_d1")
    useUpdateRows(({ args }) => {
        console.log(`useUpdateRows2`,);
        sumAmt()
    }, "p_form_ywgcwb_JL_d3")

    useDataIndexChange(({ args }) => {
        getGzdyqdByPhid(args[0]);
        const text = args[0].u_gzdy_name_EXName;
        // args[0].u_gzdy_code
        console.log(args[0]);
        if (text) {
            for (let key in window._lsz_catch_gzdyData) {
                console.log(`发现相同`, key, text);
                if (key == text) {
                    dgrid3.addRows(
                        window._lsz_catch_gzdyData[key].reduce((value, el) => {
                            //计算累计金额
                            let total_amt = 0;
                            let cnt_qty = 0;
                            if (window._lsz_catch_qty) {
                                window._lsz_catch_qty.forEach((qty_item) => {
                                    if (qty_item.u_fbht_code == el.item_no) {
                                        total_amt = qty_item.bq_qty;
                                        cnt_qty = (Number(el.qty) || 0) + (Number(el.u_bg_qty) || 0) - (Number(total_amt) || 0);
                                    }
                                });
                            }
                            if (!args[0].u_gzdy_code) {
                                args[0].u_gzdy_code = el.u_gzdy_code;
                                args[0].u_lx = el.u_lx;
                            }
                            value.push({
                                rel_key1: args[0].rel_key1,
                                u_sbqd_code: el.u_equipment_list_no,
                                u_sbqd_name_EXName: el.u_equipment_list_name,
                                u_sbqd_name: el.sbqd_phid,
                                u_danw: el.phid_unit,
                                u_danw_EXName: el.msname,
                                u_fbht_code: el.item_no,
                                u_fbqd_name_EXName: el.item_name,
                                u_fbqd_name: el.item_phid,
                                u_gzdy_code: el.u_gzdy_code,
                                u_gzdy_name_EXName: el.u_gzdy_name,
                                u_gzdy_name: el.gzdy_phid,
                                u_ljjl_qty: total_amt,
                                u_fbqd_qty: el.qty,
                                u_remain_qty: cnt_qty,
                                u_bg_qty: el.u_bg_qty,
                                u_vat_dj: el.dprc,
                                u_vat_prc:el.damt
                            });
                            return value;
                        }, [])
                    );
                }
            }
        }
        dgrid2.refreshView();
        dgrid1.refreshView();
        dgrid3.refreshView();
    }, "u_gzdy_name");

    function sumAmt() {
        const rows1 = dgrid1.getRows()
        const rows3 = dgrid3.getRows()
        let cnt_total_amt = 0
        let u_wzwg_amt = 0
        let u_mbqjh_amt = 0
        let u_mbqwg_amt = 0
        let rel_key1 = ""
        rows3.forEach(item => {
            item.u_wzwg_amt = (Number(item.u_bqjlsl) || 0) * (Number(item.u_vat_dj) || 0)
            cnt_total_amt += (Number(item.u_vat_prc) || 0)
            u_wzwg_amt += (Number(item.u_wzwg_amt) || 0)
            rel_key1 = item.rel_key1
        })
        rows1.forEach(item => {
            if (item.rel_key1 == rel_key1) {
                item.u_gzdy_amt = cnt_total_amt
                item.u_bqsj_amt = u_wzwg_amt
                item.u_wg_rate = u_wzwg_amt / cnt_total_amt

            }
            u_mbqjh_amt += (Number(item.u_gzdy_amt) || 0)
            u_mbqwg_amt += (Number(item.u_bqsj_amt) || 0)
        })
        $NG.updateState((updater) => {
            updater.data.p_form_ywgcwb_JL.setProps({
                u_mbqjh_amt: u_mbqjh_amt,
                u_mbqwg_amt: u_mbqwg_amt,
                u_mqbwg_rate: u_mbqwg_amt / mstform.getItem("u_fbht_amt").getValue(),
                u_ljwg_amt: (Number(window._catch_total_amt) || 0) + u_mbqwg_amt,
                u_ljwg_rate: (Number(window._catch_total_amt) || 0) + u_mbqwg_amt / mstform.getItem("u_fbht_amt").getValue(),
            })
        })
        dgrid1.refreshView()
        dgrid3.refreshView()
    }
    function getWgsbHeadInfo() {
        const cnt = mstform.getItem("u_fbht_name").getValue()
        if (!cnt) return
        $NG.execServer("u_fbht_name", { cnt }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            window._catch_total_amt = datas.total_amt
        })
    }
    //合同信息复位
    function rectCntInfo() {
        $NG.updateState((updater) => {
            updater.data.p_form_cnt_visa.setProps({
                u_cnt_name: "",
                u_cnt: "",
            });
        });
    }
    filterCnt();
    // 过滤合同
    function filterCnt() {
        console.log(`项目id`, headerTable.getItem("phid_pc").getValue());
        if (!headerTable.getItem("phid_pc").getValue()) return;
        $NG.updateUI((updater, state) => {
            console.log("过滤参数检查", updater);
            updater.fieldSetForm.p_form_ywgcwb_JL.u_fbht_name.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = $NG.getCmpApi("p_form_ywgcwb_JL").getItem("phid_pc").getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!headerTable.getItem("phid_pc").getValue() && {
                    clientSqlFilter: {
                        bill_type: 4, //合同类型
                        phid_pc: headerTable.getItem("phid_pc").getValue(),
                    },
                }),
            });
        });
    }
    //获取合同清单数量
    // getCntIndoByGzdyAndSbqd()
    // function getCntIndoByGzdyAndSbqd(){
    //     if(!mstform.getItem("u_cnt").getValue()) return 
    //     $NG.execServer("getCntIndoByGzdyAndSbqd",{cnt:mstform.getItem("u_cnt").getValue()},(res)=>{
    //         if(res.count == 0){return}
    //         window._cnt_qd_qty = JSON.parse(res.data).reduce((value,item)=>{
    //             value.push(item.extendObjects)
    //             return value
    //         },[])
    //         console.log(`合同清单数量缓存`);
    //     })
    // }
    editPage.oType != 'view' && getPtInfoByPhid();
    async function getPtInfoByPhid() {
        if (mstform.getItem("phid_pc").getValue()) {
            await $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(datas);
                $NG.updateState((updater) => {
                    updater.data.p_form_ywgcwb_JL.setProps({
                        //项目编码
                        u_pc_no: datas.pc_no,
                    });
                });
            });
        }
    }
    //获取合同信息
    editPage.oType != 'view' && getCntMInfoByPhid();
    async function getCntMInfoByPhid() {
        if (!mstform.getItem("u_fbht_name").getValue()) return
        await $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_fbht_name").getValue() }, async function (res) {
            if (res.count == 0) return;
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log(`合同获取`, datas, mstform.getItem("u_fbht_name").getValue());
            await $NG.updateState((updater) => {
                updater.data.p_form_ywgcwb_JL.setProps({
                    u_fbht_bo: datas.pcm_no, //合同编码
                    u_fbht_amt:datas.cnt_sum_vat,
                    //乙方单位
                    u_fbgys_name: { value: datas.supply_id, label: datas.supply_name },
                });
            });
            setTimeout(() => {
                getCntIndoByGzdyAndSbqd()
            }, 300)
        });
    }
    cntDFilter();
    function cntDFilter() {
        const phid_pcc = $NG.getCmpApi("p_form_ywgcwb_JL").getItem("phid_pc").getValue();
        if (!phid_pcc) {
            return;
        }
        $NG.updateUI((updater) =>
            updater.editGrid.p_form_ywgcwb_JL_d1.u_gzdy_name.setProps((p) => {
                return {
                    ...p,
                    editor: {
                        ...p.editor,
                        clientSqlFilter: { "m.phid_pc": $NG.getCmpApi("p_form_ywgcwb_JL").getItem("phid_pc").getValue() },
                    },
                };
            })
        );
    }

    //获取明细
    editPage.oType != 'view' && getCntIndoByGzdyAndSbqd();
    async function getCntIndoByGzdyAndSbqd() {
        const phid_pc = mstform.getItem("phid_pc").getValue();
        const cnt = mstform.getItem("u_fbht_name").getValue();
        const gys = mstform.getItem("u_fbgys_name").getValue();
        if (!phid_pc || !cnt || !gys) return;
        await $NG.execServer("getCntIndoByGzdyAndSbqd", { cnt, phid_pc, gys }, async (res) => {
            console.log(`高级明细匹配`, res);
            if (res.count == 0) return;
            const _data = JSON.parse(res.data);
            let map = {};
            _data.forEach((items) => {
                const item = items.extendObjects;
                if (!map[item.u_gzdy_name]) {
                    map[item.u_gzdy_name] = [item];
                } else {
                    map[item.u_gzdy_name].push(item);
                }
            });
            console.log(`检查参数信息`, map);
            getWgsbD3Qty()
            //缓存数据
            window._lsz_catch_gzdyData = { ...map };
            console.log(`缓存的数据`, window._lsz_catch_gzdyData);
            // const d_num = 0
            // for(let key in map){
            //     $NG.getCmpApi("toolbar_p_form_ywgcwb_JL_d1")
            // 		.getItem("addrow")
            // 		.getRef()
            // 		.click();

            // }
            //自动带出逻辑
            // //生成同步延迟
            // const sleep = 500
            // const start = new Date().getTime()+sleep
            // while(new Date().getTime()<start){
            //     //死循环同步
            // }
            // setTimeout(()=>{
            //     const d1rows= dgrid1.getRows()
            //     console.log(d1rows[0],'测试');
            //     let i = 0
            //     for(let key in map){
            //         d1rows[i].u_gzdy_name = map[key][0].gzdy_phid
            //         d1rows[i].u_gzdy_name_EXName = key
            //         console.log(key,map[key]);
            //         map[key].forEach(el => {
            //             //计算累计金额
            //             let total_amt = 0
            //             let cnt_qty = 0
            //             if(window._lsz_catch_qty){
            //                 window._lsz_catch_qty.forEach(qty_item =>{
            //                     if(qty_item.u_fbht_code == el.item_no){
            //                         total_amt = qty_item.bq_qty
            //                         cnt_qty = (Number(el.qty) || 0) - (Number(total_amt) || 0)
            //                     }
            //                 })
            //             }
            //             dgrid3.addRows({
            //                 rel_key1:d1rows[i].rel_key1,
            //                 u_sbqd_code:el.u_equipment_list_no,
            //                 u_sbqd_name:el.u_equipment_list_name,
            //                 u_danw:el.phid_unit,
            //                 u_danw_EXName:el.msname,
            //                 u_fbht_code:el.item_no,
            //                 u_fbqd_name:el.item_name,
            //                 u_gzdy_code:el.u_gzdy_code,
            //                 u_gzdy_name:el.u_gzdy_name,
            //                 u_ljjl_qty:total_amt,
            //                 u_fbsysl_qty:cnt_qty
            //             })
            //         })
            //     }
            //     dgrid1.refreshView()
            //     dgrid2.refreshView()
            // },200)
        });
    }
    //获取之前累计的数量，根据合同清单编码分类
    editPage.oType != 'view' && getWgsbD3Qty();
    async function getWgsbD3Qty() {
        const phid_pc = mstform.getItem("phid_pc").getValue();
        const cnt = mstform.getItem("u_fbht_name").getValue();
        if (!cnt || !phid_pc) return;
        $NG.execServer("getWgsbD3Qty", { phid_pc, cnt }, (res) => {
            console.log(`查找历史数量`, res);
            if (res.count == 0) return;
            const _data = JSON.parse(res.data);
            window._lsz_catch_qty = _data.reduce((value, items) => {
                const item = items.extendObjects;
                value.push(item);
                return value;
            }, []);
        });
    }

    // 根据工作单元主键获取工作单元清单
    function getGzdyqdByPhid(item) {
        $NG.execServer("getGzdyqdByPhid", { phid: item.u_gzdy_name }, (res) => {
            try {
                const data = JSON.parse(res.data)[0].extendObjects; //单返回值
                console.log(`查询功能扩展:getGzdyqdByPhid`, data);
                item.u_gzdy_code = data.u_gzdy_code;
                dgrid1.refreshView();
            } catch (error) {
                console.log(`功能扩展报错:getGzdyqdByPhid`, error);
            }
        });
    }
});

//获取合同数量
function getCntCount(table, key, fun) {
    if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
    $NG.execServer("getCntCount", { type: 4, phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
        console.log(res);
        switch (res.count) {
            case 0:
                return;
            case 1:
                const datas = JSON.parse(res.data)[0].extendObjects;
                const temp_map = {};
                temp_map[key] = datas.phid;
                temp_map[`${key}_EXName`] = datas.bill_name;
                $NG.updateState((updater) => {
                    updater.data[table].setProps({
                        ...temp_map,
                    });
                    setTimeout(() => {
                        if (fun) {
                            fun();
                        }
                    }, 200);
                });
        }
    });
}
